//
//  HRPhoneLoginViewController.m
//  Hear
//
//  Created by mac on 2017/3/28.
//  Copyright © 2017年 mac. All rights reserved.
// 登录

#import "HRPhoneLoginViewController.h"
#import "HRPhoneLoginRootView.h"
#import "HRRegestViewController.h"
#import "HRLoginModel.h"
#import "HRLoginRootViewModel.h"
#import "HearNavigationController.h"
#import "HRUpdataUserInfoModel.h"
#import "HRProtocolViewController.h"
#import "HRTabBarViewController.h"
#import "HRRegestViewModel.h"
#import "DHGuidePageHUD.h"
#import "HRTokenExpires.h"
#import "HRShowRegestToolView.h"

//#import "MyPlayTool.h"
@interface HRPhoneLoginViewController ()
@property (nonatomic, strong)HRPhoneLoginRootView *rootView;
@property (nonatomic, strong)HRLoginRootViewModel *viewModel;
@property (nonatomic, strong)HRRegestViewModel *registerModel;

@end

@implementation HRPhoneLoginViewController
#pragma mark - Get and Set
- (HRRegestViewModel *)registerModel{
    if (_registerModel == nil) {
        _registerModel = [[HRRegestViewModel alloc] init];
    }
    return _registerModel;
}


-(HRLoginRootViewModel *)viewModel
{
    if (_viewModel == nil)
    {
        _viewModel = [HRLoginRootViewModel new];
    }
    return _viewModel;
}

-(HRPhoneLoginRootView *)rootView
{
    if (_rootView == nil)
    {
        WeakSelf
        _rootView = [HRPhoneLoginRootView new];
        [self.view addSubview:(self.rootView = _rootView)];

        [_rootView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.top.bottom.mas_equalTo(0);
        }];
        _rootView.registButtonClickBlock = ^(){
            HRRegestViewController *VC = [HRRegestViewController new];
            VC.controlType = RegisterVC;
            [weakSelf.navigationController pushViewController:VC animated:YES];
            [weakSelf getConfig];
        };
        
        _rootView.forgetButtonClickBlock = ^(){
            HRRegestViewController *VC = [HRRegestViewController new];
            VC.controlType = ForgetPasswordVC;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        _rootView.loginButtonClickBlock = ^(){
            [weakSelf.view endEditing:NO];
            [weakSelf loginSightin];
            [weakSelf getConfig];

        };
        _rootView.protocolButtonClickBlock = ^(){
            HRProtocolViewController *protocolVC = [HRProtocolViewController new];
            [weakSelf.navigationController pushViewController:protocolVC animated:YES];
        };
        _rootView.otherClickBlock = ^(NSInteger index){// 第三方登录
            [weakSelf.viewModel otherLoginType:index LoginResult:^(NSDictionary *result) {
                [weakSelf otherLogin:result];
            }];
            [weakSelf getConfig];
        };

    }
    return _rootView;
}

#pragma 第三方登录
- (void)otherLogin:(NSDictionary *)resp{
    
    WeakSelf
    [self.registerModel checkIsRegisterUser:@{
                                            @"openId":resp[@"openId"],
                                            @"loginType":resp[@"loginType"],
                                            @"uuid":resp[@"usid"]
                                              } andResult:^(NSDictionary *result) {
        if (result){
            if ([result[@"CodeStatus"] intValue] == 20000){// 已注册
                DDLog(@"");
                [[NSUserDefaults standardUserDefaults]setObject:result[@"BodyContent"] forKey:@"userInfo"];
                
                HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
                [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];

                if (model.MobileNumber.length){ // 有手机号直接登录
                    [self otherLoginHear:model];
                } else {// 没有手机号 绑定手机号
                    HRRegestViewController *regestVC = [HRRegestViewController new];
                    regestVC.controlType = BindingMobileNumberVC;
                    [self.navigationController pushViewController:regestVC animated:YES];
                }
                
            } else if ([result[@"CodeStatus"] intValue] == 40005){//未注册
                DDLog(@"");
                HRRegestViewController *regestVC = [HRRegestViewController new];
                regestVC.controlType = BindingMobileNumberVC;
                regestVC.isFromRegister = YES;
                regestVC.respDict = resp;
                [self.navigationController pushViewController:regestVC animated:YES];
            }
        }
    }];
    
}


- (void)otherLoginHear:(HRUpdataUserInfoModel *)model{
    [self loginEaseMob];
    
//    [[MyPlayTool sharePlayTool] stop];
    
    [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] setObject:model.QuestionID forKey:@"QuestionID"];
    [[NSUserDefaults standardUserDefaults] setObject:model.QuestionText forKey:@"QuestionText"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserCoverPicture forKey:@"UserCoverPicture"];
    [[NSUserDefaults standardUserDefaults] setObject:model.LocalId forKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserPictureName forKey:@"iconName"];
    [[NSUserDefaults standardUserDefaults] setObject:model.UserPictureBackgroundColor forKey:@"iconColor"];
    [[NSUserDefaults standardUserDefaults] setObject:model.MobileNumber forKey:@"MobileNumber"];
    [[NSUserDefaults standardUserDefaults] setObject:model.Sex forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults] setObject:model.NickName forKey:@"nickName"];
    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:model.UserSoundUrl] forKey:@"SoundUrl"];

    [self.navigationController removeFromParentViewController];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window removeAllSubviews];
    window = nil;
    
    [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadIconAndBackGroundNotififation" object:nil];
}


- (void)loginEaseMob {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        HRUpdataUserInfoModel *infoModel = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
        EMError *error = [[EMClient sharedClient] loginWithUsername:infoModel.LocalId password:infoModel.Password];
        if (!error){
            DDLog(@"登录聊天服务器成功");
            
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            EMPushOptions *options = [[EMClient sharedClient] pushOptions];
            options.displayStyle = EMPushDisplayStyleMessageSummary;
            options.nickname = infoModel.NickName;
            [[EMClient sharedClient] updatePushOptionsToServer];
        }
        
        
    });
}

- (void)loginSightin {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WeakSelf
    HRLoginRequestModel *model = [HRLoginRequestModel new];
    model.MobileNumber = self.rootView.phoneTextField.textField.text;
    model.Password = [self.rootView.passWordTextField.textField.text md5String];
    [self.viewModel phoneLoginParam:model loginSeccess:^(BOOL loginSeccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            if (loginSeccess) {
                [weakSelf.navigationController removeFromParentViewController];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                [window removeAllSubviews];
                window = nil;
                [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadIconAndBackGroundNotififation" object:nil];
                
            }
        });
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.rootView];


    if (![[NSUserDefaults standardUserDefaults] boolForKey:BOOLFORKEY]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:BOOLFORKEY];
        
        [[NSUserDefaults standardUserDefaults] setObject:@"18" forKey:@"currentMinValue"];
        [[NSUserDefaults standardUserDefaults] setObject:@"50" forKey:@"currentMaxValue"];
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"jpushSwitch"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"easemobSwitch"];
        [HRTokenExpires getAccessToken:^(BOOL result) {
            
        }];
        
//        [[MyPlayTool sharePlayTool] loadLocalMusicUsePath:[[NSBundle mainBundle] pathForResource:@"王叔叔混音_新用户引导_v1" ofType:@"mp3"]];
        
//        NSArray *imageNameArray = @[@"引导页-1",@"引导页-2",@"引导页-3"];
//        DHGuidePageHUD *guidePage = [[DHGuidePageHUD alloc] dh_initWithFrame:self.view.frame imageNameArray:imageNameArray buttonIsHidden:YES];
//        guidePage.slideInto = YES;
//        [self.navigationController.view addSubview:guidePage];
        // 静态引导页
        
    }
    WeakSelf
    [HRShowRegestToolView showRegestToolView:^(NSInteger fromTypeIndex) {
        [weakSelf getConfig];
        if (fromTypeIndex == 0){
            
        }else if (fromTypeIndex == 1){
            HRRegestViewController *VC = [HRRegestViewController new];
            VC.controlType = RegisterVC;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }else if (fromTypeIndex == 2){
            [weakSelf.viewModel otherLoginType:0 LoginResult:^(NSDictionary *result) {
                [weakSelf otherLogin:result];
            }];
        }else if (fromTypeIndex == 3){
            [weakSelf.viewModel otherLoginType:2 LoginResult:^(NSDictionary *result) {
                [weakSelf otherLogin:result];
            }];
        }
    }];

}

- (void)getConfig {
    YTKApi *api = [YTKApi apiGetWithUrl:@"App/Get_GetSoundCardConfig" para:nil];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            
            NSDictionary *bodyContentDict = [dict[@"BodyContent"] jsonValueDecoded];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"GuidingText"] forKey:@"GuidingText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"SampleText"] forKey:@"SampleText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipText"] forKey:@"TipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TextBoxTipText"] forKey:@"TextBoxTipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipTitleText"] forKey:@"TipTitleText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"manTagList"] forKey:@"manTagList"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"womanTagList"] forKey:@"womanTagList"];
            
            DDLog(@"");
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"cacheTime"];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
